<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th><input type="checkbox" name="xqz" id="first"></th>
                <th>商品</th>
                <th>价钱</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="checkbox" name="xqz"></td>
                <td>iphone8</td>
                <td>8000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="xqz"></td>
                <td>iphone8</td>
                <td>8000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="xqz"></td>
                <td>iphone8</td>
                <td>8000</td>
            </tr>
            <tr>
                <td><input type="checkbox" name="xqz"></td>
                <td>iphone8</td>
                <td>8000</td>
            </tr>
        </tbody>
    </table>
    <script>
        // var checkboxs = document.querySelectorAll('input');
        // checkboxs[0].onclick = function () {
        //     for (let i = 0; i < checkboxs.length; i++) {
        //         if (checkboxs[0].checked = '') {
        //             checkboxs[i].checked = 'checked';
        //         } else {
        //             checkboxs[i].checked = '';
        //         }
        //     }
        // }
        var thead = document.querySelector('#first');
        var tbody = document.querySelector('tbody').querySelectorAll('input');
        thead.onclick = function () {
            if (this.checked) {
                for (let i = 0; i < tbody.length; i++) {
                    tbody[i].checked = true;
                }
            }
            if (!this.checked) {
                for (let i = 0; i < tbody.length; i++) {
                    tbody[i].checked = false;
                }
            }
        }

        for (let i = 0; i < tbody.length; i++) {
            tbody[i].onclick = function () {
                //flag控制全选按钮是否被选中
                var flag = true;
                //每次点击下面的复选框都要循环检查4个小按钮是否全被选中
                for (let i = 0; i < tbody.length; i++) {
                    if (!tbody[i].checked) {
                        flag = false;
                        break;
                    }
                }
                thead.checked = flag;

            }
        }
    </script>

</body>

</html>